package plus.easydo.starter.lock.conditional;

import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotatedTypeMetadata;
import plus.easydo.starter.lock.annotation.EnableRedisson;

/**
 * @author yuzhanfeng
 */
public class SentinelConditional implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        BeanDefinitionRegistry registry = conditionContext.getRegistry();
        String[] definitionNames = registry.getBeanDefinitionNames();
        for (String definitionName : definitionNames) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(definitionName);
            if (beanDefinition instanceof AnnotatedGenericBeanDefinition) {
                AnnotatedGenericBeanDefinition agb = (AnnotatedGenericBeanDefinition) beanDefinition;
                MergedAnnotations ans = agb.getMetadata().getAnnotations();
                if (ans.isPresent(EnableRedisson.class)) {
                    return ans.get(EnableRedisson.class).getBoolean(EnableRedisson.SENTINEL);
                }
            }
        }
        return false;
    }
}
